package com.cy.pj.sys.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.sys.entity.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/doFindPageObjects")
    public JsonResult doFindPageObjects(String username, Integer pageCurrent) {
        return new JsonResult(sysUserService.findPageObjects(username, pageCurrent));
    }

    @PostMapping("/doValidById")
    public JsonResult doValidById(Integer id, Integer valid, String modifiedUser) {
        sysUserService.validById(id, valid, modifiedUser);
        return new JsonResult("update ok");
    }

    @PostMapping("/doSaveObject")
    public JsonResult doSaveObject(SysUser entity, Integer[] roleIds) {
        sysUserService.saveObject(entity, roleIds);
        return new JsonResult("save ok");
    }

    @GetMapping("/doFindObjectById")
    public JsonResult doFindObjectById(Integer id) {
        return new JsonResult(sysUserService.findObjectById(id));
    }

    // 这个更新不会修改密码，密码是单独修改的
    @PostMapping("/doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity, Integer[] roleIds) {
        sysUserService.updateObject(entity, roleIds);
        return new JsonResult("update ok");
    }

    @PostMapping("/doLogin")
    public JsonResult doLogin(String username, String password, Boolean isRememberMe) {
        // 将用户名和密码封装到令牌对象中
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        if(isRememberMe) token.setRememberMe(true);
        subject.login(token);
        return new JsonResult("login ok");
    }

    /**
     * 修改用户密码
     * @param pwd 原密码
     * @param newPwd 新密码
     * @param cfgPwd 确认密码
     * @return
     */
    @PostMapping("/doUpdatePassword")
    public JsonResult doUpdatePassword(String pwd, String newPwd, String cfgPwd) {
        sysUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new JsonResult("update ok");
    }
}
